package com.yangye.otherdemo.printoddeven;

/**
 * @author yangye
 * @date 2020/08/17
 */
public class OddEvenPrinterDemo {

	private static final Object monitor = new Object();

	public static void main(String[] args) {
		OddEvenPrinter oddEvenPrinter = new OddEvenPrinter(0, 10);
		Thread t1 = new Thread(oddEvenPrinter);
		Thread t2 = new Thread(oddEvenPrinter);
		t1.start();
		t2.start();
	}


	static class OddEvenPrinter implements Runnable {
		private int count;
		private volatile int limit;

		public OddEvenPrinter(int count, int limit) {
			this.count = count;
			this.limit = limit;
		}

		@Override
		public void run() {
			synchronized (monitor) {
				while (count < limit) {
					try {
						System.out.println(String.format("线程%s打印%d", Thread.currentThread().getName(), count++));
						monitor.notifyAll();// 唤醒其他线程
						monitor.wait();// 挂起当前线程
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
				monitor.notifyAll();
			}
		}

	}


}
